package org.example.lc;

import java.util.*;

public class LeetCode49 {

    public static void main(String[] args) {
        String[] charArray = {"eat","tea","tan","ate","nat","bat"};
        List<List<String>> lists = groupAnagrams1(charArray);
        lists.forEach(System.out::println);
    }
    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<Integer,String> indexStr = new HashMap<>();

        for (int i = 0; i < strs.length; i++) {
            indexStr.put(i,sort(strs[i]));
        }
        Map<String,List<Integer>> result = new HashMap<>();
        indexStr.forEach((i,s)->{
            System.out.println(i+"===="+s);
            if(result.containsKey(s)){
                result.get(s).add(i);
            }else{
                List<Integer> list = new ArrayList<>();
                list.add(i);
                result.put(s,list);
            }
        });
        if(!result.isEmpty()){
            List<List<String>> resultList = new ArrayList<>();
            result.forEach((k,v)->{
                List<String> list = new ArrayList<>();
                v.forEach(i->{
                    list.add(strs[i]);
                });
                resultList.add(list);
            });
            return resultList;
        }
        return new ArrayList<>();
    }

    private static String sort(String str){
        char[] charArray = str.toCharArray();
        for (int i = 0; i < str.length(); i++) {
            for(int j = 0;j<str.length()-1;j++){
                if (charArray[j] > charArray[j+1]){
                    char temp = charArray[j];
                    charArray[j] = charArray[j+1];
                    charArray[j+1] = temp;
                }
            }
        }
        return Arrays.toString(charArray);
    }

    public static List<List<String>> groupAnagrams1(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for (String str : strs){
            String key = sort(str);
            if(map.containsKey(key)){
                map.get(key).add(str);
            }else {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(key,list);
            }
        }
        return new ArrayList<>(map.values());
    }
}
